<template>
  <c-loading :loading="loading">
    <c-form ref="afterForm">
      <view class="container after-apply">
        <view class="card">
          <order-item v-bind="data"></order-item>
        </view>
        <view class="card">
          <c-cell-box label="售后类型" @tap="onAfterType" name="afterType" arrow="down">
            <view class="inner" :class="{ gray: !afterName }">{{ afterName || '请选择售后类型' }}</view>
          </c-cell-box>
          <c-cell-box label="售后原因" v-if="resonList.length" @tap="onAfterReason" name="afterReason" arrow="down">
            <view class="inner row1" :class="{ gray: !state.afterReason }">{{ state.afterReason || '请选择售后原因' }}</view>
          </c-cell-box>
          <c-cell-box label="售后数量" name="afterQty" type="number" @change="afterQtyChange" v-model="state.afterQty"></c-cell-box>
          <c-cell-box v-if="maxReturn" label="退款金额" name="refundPrice" type="digit" @change="refundPriceChange" :disabled="disabledRefundPrice()" v-model="state.refundPrice">
            <template #break v-if="!disabledRefundPrice()">
              <view class="max-amount">
                最多可退
                <c-number :value="maxReturn" :precision="2"></c-number>
              </view>
            </template>
          </c-cell-box>
        </view>
        <view class="card upload">
          <c-cell-box label="上传凭证" name="afterImgs">
            <template #break>
              <c-upload v-model="state.afterImgs" :max-count="3" @upload="onUpload"></c-upload>
            </template>
          </c-cell-box>
        </view>
        <view class="fixed-footer flex al-center shadow">
          <c-button type="primary" @tap="onSubmit">提交申请</c-button>
        </view>
        <view class="end"></view>
      </view>
    </c-form>
    <template #popup>
      <c-popup position="bottom" v-model="textarea.show">
        <view class="popup-textarea-wrap">
          <view class="popup-textarea-title">{{ textarea.title }}</view>
          <textarea class="textarea" maxlength="100" v-model="textarea.text" :placeholder="`请输入${textarea.title}`"></textarea>
          <view><c-button type="primary" @tap="textarea.onSubmit(textarea.text)">提交</c-button></view>
        </view>
      </c-popup>
    </template>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CCellBox, CPopup, CNumber, CUpload, CForm } from '@/components';
import OrderItem from '@/pagesOrder/order/components/order-item.vue';
import { useLoading, useRouter } from '@/hooks';
import { View, Textarea, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import api from '@/api';
import { sysConfig } from '@/utils/config';
import { computed, reactive, ref, shallowRef } from 'vue';
import toast from '@/utils/toast';

const afterForm = shallowRef();
const router = useRouter();

const state = reactive({
  afterType: 0,
  afterQty: '',
  refundPrice: '',
  afterImgs: [],
  afterReason: '',
  formData: {}
});
const { loading, data } = useLoading((op, data) => {
  state.formData = data.formData;
});
const afterTypeMap = computed(() => {
  if (!data.value?.deliveryTime) {
    // 未发货
    return sysConfig.value.enums.afterType.filter(a => a.value == 5);
  }
  if (!data.value?.signTime) {
    // 未签收
    return sysConfig.value.enums.afterType.filter(a => a.value != 5 && a.value != 2);
  }
  return sysConfig.value.enums.afterType.filter(a => a.value != 5 && a.value != 3 && a.value != 2);
});

const textarea = reactive({
  show: false,
  text: '',
  title: '',
  onSubmit(e) {}
});
const onUpload = (file, onProgress) => {
  return api.file.upload('user', file, { onProgress }).finally(() => {
    afterForm.value.changeError('afterImgs');
  });
};
const disabledRefundPrice = () => {
  return state.afterType == 2 || state.afterType == 5 || state.afterType == 6;
};

const maxReturn = computed(() => {
  if (!data.value) return 0;
  if (state.afterType == 2 || state.afterType == 6) {
    return 0;
  }
  return parseFloat((((data.value.goodsAmount - data.value.discountAmount) / data.value.qty) * state.afterQty).toFixed(2));
});

const afterName = computed(() => {
  return afterTypeMap.value.find(a => a.value == state.afterType)?.name;
});

const afterQtyChange = qty => {
  let nq = data.value.qty - data.value.afterSaleSuccessQty - data.value.afterSaleQty;
  if (qty > nq) {
    state.afterQty = nq;
  }
  afterForm.value.changeError('afterQty');
  resetRefund();
};
const resetRefund = () => {
  state.refundPrice = maxReturn.value;
  afterForm.value.changeError('refundPrice');
};

const refundPriceChange = price => {
  if (price > maxReturn.value) {
    state.refundPrice = price;
  }
};
const onAfterType = () => {
  Taro.showActionSheet({
    itemList: afterTypeMap.value.map(a => a.name),
    success(r) {
      state.afterType = afterTypeMap.value[r.tapIndex].value;
      state.afterReason = '';
      // state.afterQty = 1;
      afterForm.value.changeError('afterType');
      // afterForm.value.changeError('afterQty');
      // resetRefund();
    }
  });
};

// 退货退款=1,换货=2,仅退款=3,仅补偿=4,取消商品=5,漏发补发=6
const resonMap = {
  不想要了: [1, 3],
  商品信息描述不符: [1],
  与商家协商一致: [1, 2, 3, 4],
  '包装/商品破损/污渍': [1, 2, 3, 4],
  未按约定时间发货: [3],
  拍错商品: [5],
  其他原因: [1, 2, 3, 4, 5]
};
const resonList = computed(() =>
  Object.entries(resonMap)
    .filter(([name, v]) => v.includes(state.afterType))
    .map(([name, v]) => name)
);
const onAfterReason = () => {
  Taro.showActionSheet({
    itemList: resonList.value,
    success(r) {
      var reson = resonList.value[r.tapIndex];
      if (reson == '其他原因') {
        textarea.show = true;
        textarea.title = '售后原因';
        textarea.text = '';
        textarea.onSubmit = text => {
          if (!text) {
            return toast.success('请输入售后原因', true);
          }
          textarea.show = false;
          state.afterReason = text;
          afterForm.value.changeError('afterReason');
        };
        return;
      }
      state.afterReason = reson;
      afterForm.value.changeError('afterReason');
    }
  });
};

const onSubmit = () => {
  return api.order.aftersalesUserApply({ ...state, orderNo: data.value.orderNo, itemId: data.value.id }).then(data => {
    router.back({});
  });
};
</script>
<style lang="scss">
.container.after-apply {
  padding-top: 20px;
  .card {
    padding: 0;
    .input {
      text-align: right;
    }
    .title {
      font-size: 28px;
      font-weight: bold;
      padding: 20px 30px 0;
    }
    &.upload .break {
      padding: 0;
      .upload-wrap {
        padding-top: 0;
      }
    }
  }
  .max-amount {
    color: var(--color-gray);
    font-size: 24px;
    text-align: right;
  }
  .inner {
    font-size: 30px;
    text-align: right;
    padding-right: 10px;
    &.gray {
      color: var(--color-gray2);
    }
  }
}
</style>
